/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.indexdatasource.dao;

import java.util.Collection;
import java.util.List;

import com.pingan.haofang.searchcloud.dashboard.dto.IndexDatasourceGroupDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pingan.haofang.searchcloud.indexdatasource.domain.IndexDatasource;

/**
 * 索引构建数据库访问层
 *
 * @author zhangbi617
 * @date 04/05/2017
 */
@Repository
public interface IndexDatasourceDao extends JpaRepository<IndexDatasource, Long> {

    /**
     * 根据indexId来查
     *
     * @param indexId 索引Id
     * @return
     */
    @Query("from IndexDatasource datasource where datasource.indexId = :indexId and datasource.status = :status")
    List<IndexDatasource> findByIndexId(@Param("indexId") Long indexId, @Param("status") int status);

    /**
     * 根据indexId 和 name 来查
     *
     * @param indexId 索引ID
     * @param name    数据源名称
     * @return
     */
    @Query("from IndexDatasource datasource where datasource.indexId = :indexId and datasource.name = :name and datasource.status = :status")
    List<IndexDatasource> findByIndexIdAndName(@Param("indexId") Long indexId, @Param("name") String name, @Param("status") int status);


    /**
     * 更新数据源状态
     *
     * @param id     数据源ID
     * @param status 数据源状态
     * @param opId   操作人
     */
    @Modifying(clearAutomatically = true)
    @Query("update IndexDatasource i set i.status = :status , i.updateBy = :opId where i.id = :id ")
    void updateStatus(@Param("id") Long id, @Param("status") int status, @Param("opId") Long opId);


    /**
     * 根据indexId列表查询数据源列表
     *
     * @param indexIdList indexId列表
     * @param status
     * @return
     */
    @Query("from IndexDatasource datasource where datasource.indexId IN(:indexIds) and datasource.status = :status")
    List<IndexDatasource> findByIndexIds(@Param("indexIds") Collection<Long> indexIdList, @Param("status") Integer status);

    /**
     * 统计index数据源
     * @param status
     * @return
     */
    @Query("select new com.pingan.haofang.searchcloud.dashboard.dto.IndexDatasourceGroupDto(a.indexId,count(a)) " +
            "from IndexDatasource a where  a.status= :status group by a.indexId")
    List<IndexDatasourceGroupDto> findByStatus(@Param("status")Integer status);
}
